<template>
  <div class="dfForm" :class="formConfig.title&&formConfig.title!=''?'form-border':''">
    <div class="form-title" v-if="formConfig.title&&formConfig.title!=''">
      {{formConfig.title}}
    </div>
    <div :class="formConfig.title&&formConfig.title!=''?'form-body':''">
      <el-form
        class="dynamic-form"
        v-bind="formConfig"
        :inline="formConfig.inline"
        ref="ruleForm"
        :model="value"
        :label-position="formConfig.labelPosition"
        :label-width="formConfig.labelWidth?formConfig.labelWidth:'30%'"
        :size='formConfig.size'
        :status-icon="formConfig.statusIcon"
        :hide-required-asterisk="false"
        :validate-on-rule-change="false">
        <slot name="before"></slot>
        <el-row :gutter="24" style="text-align:right;">
          <df-element-form-item
            :class="item.hide?'hide':''"
            :ref="item.key+'-fileds'"
            v-if="!(item.start || item.end) || hackReset"
            v-for="item in formConfig.formItemList"
            :key="item.key"
            :item="item"
            :type="item.type"
            :subtype="item.subtype"
            :formDisabled="formConfig.disabled"
            v-bind="item"
            :value="value[item.key]"
            :title="value[item.key]"
            :file-list="(item.subtype == 'upload' || item.subtype == 'picture-card') ? value[item.key] : []"
            :src="value[item.key]"
            :style="{'min-width':columnMinWidth}"
            @handelChange="handelChange"
            @input="handleInput({ val: $event, key: item.key, item: item })"
          ></df-element-form-item>
        </el-row>
        <slot></slot>
      </el-form>
    </div>
  </div>
</template>
<script>
// import { deepClone } from '@/util/util'
export default {
  props: {
    formConfig: {
      type: Object,
      required: true
    },
    value: {
      type: Object
    },
    columnMinWidth: {
      type: String,
    },
  },
  data() {
    return {
      formData: {},
      hackReset: true
    }
  },
  created() {
    this.setDefaultValue()
  },
  watch:{
    formConfig: {
      deep: true, // 深度监听
      immediate:true,
      handler(val) {
        // console.log('formConfigwatch',val)
        this.setDefaultValue()
      }
    },
    value: {
      deep: true, // 深度监听
      immediate:true,
      handler(val) {
        // console.log(val)
        // this.setDefaultValue()
      }
    }
  },
  methods: {
    handelChange(data) { // val, key, item
      let _this = this,
          value = data.val    
      if (data.hasOwnProperty('item')) {
        if (data.item.type === 'cascader' && data.val && data.val.length > 0) {
          value = data.val[data.val.length - 1]
        }   
        _this.$emit('changeEvent', { item: data.item, key: data.key, val: value })
        _this.$set(_this.value, data.key, value)   
        if (data.item.start || data.item.end) {
          _this.checkRangeDate()
        }  
      } else {
        _this.$set(_this.value, data.key, value)     
        for (let index = 0; index < _this.formConfig.formItemList.length; index++) {
          const element = _this.formConfig.formItemList[index];
          if (element.key === data.key) {
            _this.$emit('changeEvent', { item: element, key: data.key, val: value })
          }
        }
      }     
    },
    handleInput(data) { // val, key, item
      let _this = this,
          value = data.val    
      if (data.hasOwnProperty('item')) {
        if (data.item.type === 'cascader' && data.val && data.val.length > 0) {
          value = data.val[data.val.length - 1]
        }   
        _this.$emit('changeEvent', { item: data.item, key: data.key, val: value })
        _this.$set(_this.value, data.key, value)   
        if (data.item.start || data.item.end) {
          _this.checkRangeDate()
        }  
      } else {
        _this.$set(_this.value, data.key, value)     
        for (let index = 0; index < _this.formConfig.formItemList.length; index++) {
          const element = _this.formConfig.formItemList[index];
          if (element.key === data.key) {
            _this.$emit('changeEvent', { item: element, key: data.key, val: value })
          }
        }
      }      
    },
    setDefaultValue() {
      var _this = this;
      if (_this.value === undefined) {
        _this.value = {}
      }
      if(_this.formConfig && _this.formConfig.hasOwnProperty('formItemList')) {
        _this.formConfig.formItemList.forEach(item => {
          const { key, value } = item;
          if (item.type != 'divider') {
            if(item.type == "cascader" || item.subtype == "picture-card" || item.subtype == "upload"){
              if (_this.value[key] === undefined || _this.value[key] === null || _this.value[key] === "") {
                _this.$set(_this.value, key, [])
              }
            }else{
              if (_this.value[key] === undefined || _this.value[key] === null || _this.value[key] === "") {
                _this.$set(_this.value, key, value)
              }
            }      
            if (item.hasOwnProperty('set') && item['set'] != '') {
              _this.$emit('changeEvent', { item: item, key: key, val: _this.value[key], isSetNull: false })
            } else {
              _this.$emit('changeEvent', { item: item, key: key, val: _this.value[key] })
            }
          }       
        })
      }    
      console.log(_this.value);
    },
    // 校验数据
    validateForm () {
      let flag = null,
        _this = this
      _this.$refs['ruleForm'].validate((valid, object) => {
        console.log(object)
        if (valid) {
          flag = true
        } else {
          flag = false
          for (let i in object) {
            let dom = this.$refs[i+'-fileds'];            
            if (Object.prototype.toString.call(dom) !== '[object Object]') { //这里是针对遍历的情况（多个输入框），取值为数组
              dom = dom[0];
            }
            dom.$el.scrollIntoView({  // 滚动到指定节点
              block: 'center', // 值有start,center,end，nearest，当前显示在视图区域中间
              behavior: 'smooth' // 值有auto、instant,smooth，缓动动画（当前是慢速的）
            })
            break; //因为我们只需要检测一项,所以就可以跳出循环了
          }
        }
      })
      return flag
    },
    // 清除校验
    clearValidate (prop) {
      if(prop) {
        let _field = this.$refs['ruleForm'].fields /*当然，你可以打印一下fields*/
        for (let j = 0; j < prop.length; j++) {
           _field.map(i => {
            if(i.prop === prop[j]){  //通过prop属性值相同来判断是哪个输入框，比如：要移除prop为'user'
              i.resetField() 
              return false
            }
          })
        }
      }else{
        let _field = this.$refs['ruleForm'].fields /*当然，你可以打印一下fields*/
        _field.map(i => {
          i.resetField() 
        })
      }
    },
    // 表单重置，移除校验结果
    resetFieldsForm () {
      this.$refs['ruleForm'].resetFields()
    },
    checkRangeDate () {
      let rangeDate = {
        startDate: {
          index: 0,
          value: '',
          label: '开始时间'
        },
        endDate: {
          index: 0,
          value: '',
          label: '结束时间'
        }
      }

      for (let index = 0; index < this.formConfig.formItemList.length; index++) {
        const element = this.formConfig.formItemList[index];
        if (element.start) {
          rangeDate.startDate.index = index
          rangeDate.startDate.label = element.label
          rangeDate.startDate.value = this.value[element.key]
        } else if(element.end) {
          rangeDate.endDate.index = index
          rangeDate.endDate.label = element.label
          rangeDate.endDate.value = this.value[element.key]
        }
      }

      console.log(rangeDate);
      if(rangeDate.startDate.value != '' && rangeDate.endDate.value != '') {
        if(rangeDate.startDate.value > rangeDate.endDate.value) {
          this.$set(this.formConfig.formItemList[rangeDate.startDate.index], 'errorMsg', rangeDate.startDate.label + '需小于' + rangeDate.endDate.label)
          this.$set(this.formConfig.formItemList[rangeDate.endDate.index], 'errorMsg', rangeDate.startDate.label + '需小于' + rangeDate.endDate.label)
        } else {
          this.$set(this.formConfig.formItemList[rangeDate.startDate.index], 'errorMsg', '')
          this.$set(this.formConfig.formItemList[rangeDate.endDate.index], 'errorMsg', '')
        }
      } else {
        this.$set(this.formConfig.formItemList[rangeDate.startDate.index], 'errorMsg', '')
        this.$set(this.formConfig.formItemList[rangeDate.endDate.index], 'errorMsg', '')
      }
      this.hackReset = false
      this.$nextTick(() => {
        this.hackReset = true
      })
    }
  }
}
</script>

<style>
.el-select {
  width: 100%;
}
.el-cascader {
  width: 100%;
}
</style>